package com.csx.governance.traffic.core.support;

import cn.hutool.core.lang.Assert;
import com.csx.governance.traffic.core.TrafficMessageParameterExtractor;
import com.csx.governance.traffic.core.context.TrafficMessage;
import com.csx.governance.traffic.core.context.servlet.TrafficHttpServletRequest;
import org.springframework.util.LinkedCaseInsensitiveMap;

import javax.servlet.http.HttpServletRequest;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;

/**
 * <p>Http请求头解析器</p>
 * <p>解析 {@link HttpServletRequest} 中Header的解析器，主要作用是将 {@link HttpServletRequest}中的Header放入到一个Map中</p>
 * @author cuisongxu
 * @date 2023/4/2 16:32
 */
public class HttpServletRequestHeaderExtractor implements TrafficMessageParameterExtractor {

    @Override
    public Map<String, Object> extract(TrafficMessage trafficMessage) {
        HttpServletRequest originRequest = trafficMessage.getOriginMessage(HttpServletRequest.class);
        Assert.notNull(originRequest, "current HttpServletRequestHeaderExtractor not support this request type: " + trafficMessage);

        Map<String, Object> headers = new LinkedCaseInsensitiveMap<>();
        Enumeration<String> headerNames = originRequest.getHeaderNames();
        Map<String, String> temp = new HashMap<>(16);
        while (headerNames.hasMoreElements()) {
            String headerName = headerNames.nextElement();
            String headerValue = originRequest.getHeader(headerName);
            temp.put(headerName, headerValue);
        }
        headers.putAll(temp);
        return headers;
    }

    @Override
    public Boolean isSupport(Class<?> clazz) {
        return clazz.equals(TrafficHttpServletRequest.class);
    }

    @Override
    public ParameterSource parameterSource() {
        return ParameterSource.HEADER;
    }
}
